/**
*@author Miguel Soares de Lima @ 09/22/2008
*/
public class DiscussionForumSubscribersEmailServices {

	//E-mail services instance
	private Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    private DiscussionMember__c dm = new  DiscussionMember__c();
	private List<DiscussionForumSubscription__c> TeamMemberSubscription = new List<DiscussionForumSubscription__c>();	
	private String url = '';

	public Boolean isTaskEdit = false;
	public Boolean isTest = false;
	
	/**
	* Constructor (def)
	*/
	public DiscussionForumSubscribersEmailServices(){
	
		PageReference PR =  ApexPages.currentPage(); 
		
		String newPath ='';
		//In Gannt Page Reference is null
		if(PR !=  null){
			String props = '';
			if(PR.getHeaders() != null){
				props = (PR.getHeaders()).get('Host');
			}
			//Remove HTML tag of Path
			if (props == '' || props == null) {
				newPath = '';	
			}else {
				String [] path = props.split('</?[a-z][a-z0-9]*[^<>]*>');
				if(path.size() == 0){
					newPath = path[0];
				}else{
					for(Integer i = 0; i < path.size(); i++){	
						newPath += path[i];
					}
				}
			}
		}
		this.url = newPath;
	}

	/**
	*@param Boolean isTest
	*/
	public void setIsTest ( Boolean isTest ) 
	{
		this.isTest = isTest;	
	}
	
	/**
	*@param Boolean
	*/
	public void setIsTaskEdit ( Boolean isTaskEdit ){
		this.isTaskEdit = isTaskEdit;
	}


	/**
	*Sends email when a member leave or join to a fourm
	*@param String action
	*@param String id
	*/
	public void sendMemberLeaveAdd( String acction, String idDiscussionMember )
	{
		
		String emailMsj = '';
		String emailSub = '';
		
		if ( acction == 'TeamMemberJoin' || acction == 'TeamMemberAdd' || acction == 'TeamMemberLeave') 
		{	
			
			DiscussionMember__c dm = new DiscussionMember__c();
			dm = [ SELECT Id, DiscussionForum__c, User__c, DiscussionForum__r.Name, User__r.Name FROM DiscussionMember__c WHERE Id =: idDiscussionMember ];
			
			if ( acction == 'TeamMemberLeave') 
			{
				//Sub:Team Member has Left the team
				//Body: {Name} has left team {team name} 
				String oldMemberName = dm.User__r.Name;
				emailMsj = oldMemberName + 'さんが、フォーラム<a href="https://' + url + '/apex/DiscussionTopics?id=' + dm.DiscussionForum__c + '">' +  dm.DiscussionForum__r.Name + '</a>から登録解除されました';
				emailSub = 'メンバーがフォーラムのメンバーから登録解除されました。 ';
			}
			else 
			{
				//Sub:New Team Member
				//Body: A new team member has joined team {}. Please welcome {name} to the team.
				emailMsj = '新しいメンバーがフォーラム<a href="https://'+ url + '/apex/DiscussionTopics?id=' + dm.DiscussionForum__c + '">' +  dm.DiscussionForum__r.Name + '</a>に追加されました。' + dm.User__r.Name + 'さん ようこそ！';
				emailSub = '新しいメンバーがフォーラムに追加されました';
			}

			if (!isTest) {
				TeamMemberSubscription = [Select 
					t.User__c, 
					t.User__r.Id,
					t.User__r.Name,
					t.User__r.Email,
					t.Team__c,
					t.Team__r.Name,
					t.Team__r.Id, 
					t.TeamMemberStatusUpdated__c,
					t.TeamMemberJoinLeave__c,
					t.Id, 
					t.DiscussionReplyToMe__c, 
					t.DiscussionNewTopic__c, 
					t.DiscussionNewReply__c
					From DiscussionForumSubscription__c t
					where Team__c =: dm.DiscussionForum__r.Id and TeamMemberJoinLeave__c = true];
			}

			genAddress( TeamMemberSubscription, emailMsj, emailSub );

		}
	}

	/**
	*Sends email when a new topic is created 
	*@param String id
	*@param String action   
	*/
	public void sendNewTopicMessage( String IdNewTopic, String acction )
	{
	    DiscussionTopic__c dm = new  DiscussionTopic__c();
		List<DiscussionMessage__c> newTopicList = new List<DiscussionMessage__c>();	

		newTopicList = [select DiscussionTopic__c, DiscussionTopic__r.Subject__c, Message__c, Discussion__c from DiscussionMessage__c where DiscussionTopic__c=:IdNewTopic order by PostedDate__c];
		dm = [ SELECT Id, DiscussionForum__c, DiscussionForum__r.Name, Name FROM DiscussionTopic__c WHERE Id =: IdNewTopic ];
		
		System.debug( '@@@: ' + idNewTopic );
		
		String topicSubject = '';
		String topicBody    = '';
		if ( newTopicList.size() > 0 ) 
		{
			topicSubject = newTopicList[0].DiscussionTopic__r.Subject__c;
			topicBody = newTopicList[0].Message__c;
		}
		
		String linkToDiscussion = '<a href="https://'+ url +'/apex/discussiontopics?id=' + newTopicList[0].Discussion__c + '">フォーラムへのリンク</a>.<br />';
		String linkToTopic = '<a href="https://'+ url +'/apex/DiscussionDetail?id=' + idNewTopic + '">トピックへ返信</a>。<br />';
		String linkToSubcription = '<a href="https://'+ url +'/apex/DiscussionForumSubscription?id=' + idNewTopic + '">購読設定の変更</a>.<br />';
		
		String emailSub = '';
		if( acction == 'update' )
		emailSub = 'Update of: ';
		emailSub += topicSubject + 'がフォーラム:' +  dm.DiscussionForum__r.Name + 'に登録されました';
		String emailMsj = 'トピック<a href="https://' + url +'/apex/DiscussionDetail?id=' + idNewTopic + '">' + newTopicList[0].DiscussionTopic__r.Subject__c + 
		'</a>がフォーラム:<a href="https://' + url +'/apex/DiscussionTopics?id=' + dm.DiscussionForum__c + '">' + dm.DiscussionForum__r.Name + '</a>に登録されました<br /> <br />'
		+ topicBody + 'このトピックに返信するには、 <a href="https://' + url + '/apex/DiscussionDetail?id=' + idNewTopic + 
		'">ここ</a>をクリックしてください。 購読設定を変更される場合は、' + '<a href="https://'+ url +'/apex/DiscussionForumSubscription?id=' + idNewTopic + ' ">ここ</a>から変更してください。';
				
		if (!isTest) {
			TeamMemberSubscription = [Select 
				t.User__c, 	t.User__r.Id, t.User__r.Name, t.User__r.Email, t.Team__c, t.Team__r.Name, t.Team__r.Id,  t.TeamMemberStatusUpdated__c, t.TeamMemberJoinLeave__c, t.Id, t.DiscussionReplyToMe__c, t.DiscussionNewTopic__c, t.DiscussionNewReply__c From DiscussionForumSubscription__c t  where Team__c =: dm.DiscussionForum__c and (DiscussionNewTopic__c = true or DiscussionNewReply__c = true)];
		}
		genAddress( TeamMemberSubscription, emailMsj, emailSub );

	}

	/**
	*Sends email when a new reply is posted
	*@param String id
	*@param String action   
	*/
	public void sendNewReplyMessage( String idNewReplay , String acction )
	{
		
	    DiscussionMessage__c dm = new  DiscussionMessage__c();
		List<DiscussionMessage__c> newTopicList = new List<DiscussionMessage__c>();
		newTopicList = [select ParentMessage__r.Message__c, ParentMessage__c, Subject__c, DiscussionTopic__c, DiscussionTopic__r.Subject__c, Message__c from DiscussionMessage__c where id =: idNewReplay ];
		dm = [ SELECT Id, DiscussionTopic__r.DiscussionForum__c, DiscussionTopic__r.DiscussionForum__r.Name  FROM DiscussionMessage__c WHERE Id =: idNewReplay ];

		String topicSubject = '';
		String topicBody = '';
		String respondingTo = '';
		if (newTopicList.size() > 0) 
		{
			topicSubject = newTopicList[0].DiscussionTopic__r.Subject__c;
			topicBody = newTopicList[0].Message__c;
			if (newTopicList[0].ParentMessage__c != null) 
			{
 				respondingTo = newTopicList[0].ParentMessage__r.Message__c;
			}
			else 
			{
				List<DiscussionMessage__c> parentTopic = [select Message__c from DiscussionMessage__c where DiscussionTopic__c =:newTopicList[0].DiscussionTopic__c order by PostedDate__c];
				if (parentTopic.size() > 0) 
				{
					respondingTo = parentTopic[0].Message__c;
				}
			}
		}
				
		String emailSub = '';
		
		if( acction == 'update' )
		emailSub = 'Update of ';
		
		emailSub += 'RE: ' + topicSubject + 'がフォーラム:' +  dm.DiscussionTopic__r.DiscussionForum__r.Name + 'に登録されました。';
		String emailMsj = topicBody;
		emailMsj += '<br>.......返信先.....<br>';
		emailMsj += respondingTo;
				
				
		List<DiscussionForumSubscription__c> TmpTeamMemberSubscription = new List<DiscussionForumSubscription__c>();
		List<DiscussionForumSubscription__c> Tmp2TeamMemberSubscription = new List<DiscussionForumSubscription__c>();
		if (!isTest) 
		{
			TmpTeamMemberSubscription = [Select 
				t.User__c, t.User__r.Id, t.User__r.Name, t.User__r.Email, t.Team__c, t.Team__r.Name, t.Team__r.Id, 
				t.TeamMemberStatusUpdated__c, 
				t.TeamMemberJoinLeave__c, 
				t.Id, 
				t.DiscussionReplyToMe__c, 
				t.DiscussionNewTopic__c, 
				t.DiscussionNewReply__c
				From DiscussionForumSubscription__c t
				where Team__c =: dm.DiscussionTopic__r.DiscussionForum__c ];
		}
		String DiscussionTopicOwnerId = [Select d.PostedBy__c From DiscussionTopic__c d where ( Id =: newTopicList[0].DiscussionTopic__c )][0].PostedBy__c;
		for(DiscussionForumSubscription__c tmp : TmpTeamMemberSubscription){
			if(tmp.DiscussionNewReply__c == true){
				TeamMemberSubscription.add(tmp);
			}
			else if(tmp.DiscussionReplyToMe__c == true && tmp.User__r.Id == DiscussionTopicOwnerId){
				TeamMemberSubscription.add(tmp);
			}
		}
		genAddress( TeamMemberSubscription, emailMsj, emailSub );
		

	}

	/**
	*Generate address to send emails
	*@param List<DiscussionForumSubscription__c>
	*@param String
	*@param String
	*/
	public void genAddress( List<DiscussionForumSubscription__c> TeamMemberSubscription, String emailMsj, String emailSub )
	{
		//Array address
		String[] address = new String[]{}; 
		Integer it = 0;
		if(TeamMemberSubscription.size() > 10){
			for(Integer i =0; i < TeamMemberSubscription.size(); i++ ){	
				if(it < 10 || i == TeamMemberSubscription.size() ){
					address.add(TeamMemberSubscription[i].User__r.Email);
					it ++;
				}else{
					SendMail(address, TeamMemberSubscription[0].Team__r, emailMsj, emailSub);
					it = 0;
				}
			}
		}
		else 
		if(TeamMemberSubscription.size() > 0 && TeamMemberSubscription != null)
		{	
			for(DiscussionForumSubscription__c ts : TeamMemberSubscription )
			{
				address.add(ts.User__r.Email);
			}
			SendMail(address, TeamMemberSubscription[0].Team__r, emailMsj, emailSub);
		}
	
	}
	
	
	/**
	* SEND MAIL
	*@param String[] e-mails Array
	*@param Team__c team
	*@param String message
	*@param String subject
	*/
	Boolean alreadySent = false;
	public void SendMail(String[] toAddresses , DiscussionForum__c team,  String Message, String subject) {
 		// Assign thsetReplyToe addresses for the To and CC lists to the mail object.
		mail.setToAddresses(toAddresses);
		
		mail.setCharset('ISO-2022-JP');
		
		// Specify the address used when the recipients reply to the email.
		mail.setReplyTo('forwardtosfdc@gmail.com');
 		// Specify the name used as the display name.
		mail.setSenderDisplayName('Team Subscribe');  
		//Specify the subject line for your email address.
		mail.setSubject(subject);

		mail.setSenderDisplayName(team.Name);
		// Set to True if you want to BCC yourself on the email.
		mail.setBccSender(false);
		// Optionally append the salesforce.com email signature to the email.
		// The email address of the user executing the Apex Code will be used.
		mail.setUseSignature(true); 
		//Set Content Mail
		mail.setHtmlBody(Message);
		// Send the email you have created.
        if(!alreadySent)
        	Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
    	alreadySent = true;
    }
}